﻿using Entity;
using Global;
using Global.ExtensionMethods;
using Help.GLB.Global;
using Microsoft.EntityFrameworkCore;
using ViewModels.Components;
using ViewModels.User;

namespace ProdService
{
    public class PhoneService : BaseService
    {
        const int expireMinutes = 10;

        public PhoneService(DbContext dbContext) : base(dbContext)
        {
        }
        public Phone GetBy(string number)
        {
            return dbContext.Set<Phone>().
                Where(p => p.Number == number).SingleOrDefault();
        }

        public bool Send(string number)
        {
            Phone phone = GetBy(number);
            if (phone == null)
            {
                phone = new Phone
                {
                    Number = number
                };
                dbContext.Add<Phone>(phone);
                dbContext.SaveChanges();
            }//else nothing
            return sendSMS(phone, Config.Template.SMS.Register);
        }

        /// <summary>
        /// 检查短信验证码
        /// </summary>
        /// <param name="phoneNumber">手机号码</param>
        /// <param name="smsCode">短信验证码</param>
        /// <returns>错误消息，null表示通过验证</returns>
        public string CheckToken(string phoneNumber, string smsCode)
        {
            Phone phone = GetBy(phoneNumber);
            string message = string.Empty;
            if (phone == null)
            {
                message = "* 没有该电话号码";
            }
            else if (phone.ExpiredTime < DateTime.Now)
            {
                message = "* 短信验证码过期";
            }
            else if (phone.CheckCode != smsCode)
            {
                message = "* 短信验证码错误";
            }

            return message;
        }

        private bool sendSMS(Phone phone, string template)
        {
            try
            {
                bool success = false;

                phone.SetCheckCode(expireMinutes);
                if (phone.Number.StartsWith("100000000"))
                {
                    success = true;
                    phone.ResponseMessage = "测试号码……";
                }
                else
                {
                    success = PhoneHelper.Send(template,
                        new string[] { phone.CheckCode, expireMinutes.ToString() },
                        new string[] { $"+86{phone.Number}" },
                        out string response);
                    phone.SendSuccess = success;
                    phone.ResponseMessage = response;
                }
                phone.SendSuccess = success;
                return success;
            }
            catch (Exception e)
            {
                phone.ResponseMessage = e.ToString();
                //EmailHelper.ToAdmin($"发送短信给（{phone.Number}）时出错", e.ToString());
                return false;
            }
        }
    }
}